package com.lyn.utils;

import android.annotation.SuppressLint;
import android.os.Build;
import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 改密工具类
 * @author longyn 2022/12/29
 * @version 1.0.0
 */
public class AESUtil {

    //获取Cipher对象的算法
    private static final String transformation = "AES/ECB/PKCS5Padding";
    private static String defaultKey = "hgsakfgq87430915";

    public static void init(String key) {
        defaultKey = key;
    }

    /**
     * 加密
     *
     * @param input     明文
     * @param key       密钥(AES,密钥的长度必须是16个字节)
     * @param algorithm 获取密钥的算法
     * @return 返回密文
     */
    public static String encrypt(String input, String key, String algorithm) throws Exception {
        // 1,获取Cipher对象
        @SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance(transformation);
        // 指定密钥规则
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        // 2.初始化向量的秘钥长度需要根据算法而定,des 8个字节长度  aes 16个字节长度
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        // 3. 加密
        byte[] bytes = cipher.doFinal(input.getBytes());
        // 对数据进行Base64编码
        return Base64.encodeToString(bytes,Base64.DEFAULT);
    }

    /**
     * 解密
     *
     * @param input     密文
     * @param key       密钥(AES,密钥的长度必须是16个字节)
     * @param algorithm 获取密钥的算法
     * @return 返回原文
     */
    public static String decrypt(String input, String key, String algorithm) throws Exception {
        @SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance(transformation);
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        byte[] bytes = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
        return new String(bytes);
    }

    public static String encrypt(String input) {
        try {
            return encrypt(input, defaultKey, "AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String input) {
        try {
            return decrypt(input, defaultKey, "AES");
        } catch (Throwable ignored) {
        }
        return null;
    }

}
